package com.home.scheduler;

import com.home.base.util.FetchCoinUtil;
import com.home.base.util.FetchUtil;
import com.home.base.util.PhoneFetchUtil;
import com.home.biz.PhoneBiz;
import com.home.config.InitDataConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * @author ：chenxf
 * @date ：Created in 2019/6/13 14:27
 * @description：启动线程
 * @modified By：
 * @version: $
 */
@Slf4j
@Component
public class InitScheduler {
    @Autowired
    PhoneBiz phoneBiz;

    private String data="{\"MsgType\":\"LiveHKSelectNumberReq\",\"Version\":\"1.0.0\",\"provCode\":\"#PROV\",\"cityCode\":\"#CITY\",\"selecttype\":0,\"searchkey\":\"\",\"count\":10}";

    //每天0点更新一次redis中的站点信息
    @Scheduled(cron = "0/1 *  * * * ?")
    public void init() {
        //log.debug(" 下单 scheduler init");
        //log.debug(" 下单 scheduler init");
        if(StringUtils.isEmpty(InitDataConfig.getToken())){
            log.debug(" error token");
            return;
        }

        //TODO fetch

        try {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("HHmmss");
            String time = df.format(now);

            if(Integer.valueOf(time)>=Integer.valueOf(InitDataConfig.getStartTime()) && Integer.valueOf(time)<=Integer.valueOf(InitDataConfig.getEndTime()) ) {
                 new FetchCoinUtil(InitDataConfig.getToken()).price();

                   // buy(price);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

      //  log.debug("下单 scheduler finished");
        //log.debug("下单 scheduler finished");
    }

    public void buy(String price) throws Exception{

        while (InitDataConfig.getNum() > 0) {
               log.debug(" buy mission num ={}",InitDataConfig.getNum());
                boolean result = new FetchCoinUtil(InitDataConfig.getToken(), InitDataConfig.getVeryCode(), price).fetch();
                if (result) {
                    int num = Integer.valueOf(InitDataConfig.getNum());
                    InitDataConfig.setNum((num - 1));
                }
        }
    }
}

